package com.lyy.lottery.controller;

import com.lyy.lottery.common.errorcode.ControllerErrorCodeConstants;
import com.lyy.lottery.common.exception.ControllerException;
import com.lyy.lottery.common.exception.ServiceException;
import com.lyy.lottery.common.pojo.CommonResult;
import com.lyy.lottery.common.util.JacksonUtil;
import com.lyy.lottery.controller.param.ShortMessageLoginParam;
import com.lyy.lottery.controller.param.UserPasswordLoginParam;
import com.lyy.lottery.controller.param.UserRegisterParam;
import com.lyy.lottery.controller.result.BaseUserInfoResult;
import com.lyy.lottery.controller.result.UserLoginResult;
import com.lyy.lottery.controller.result.UserRegisterResult;
import com.lyy.lottery.service.UserService;
import com.lyy.lottery.service.VerificationCodeService;
import com.lyy.lottery.service.dto.UserDTO;
import com.lyy.lottery.service.dto.UserLoginDTO;
import com.lyy.lottery.service.dto.UserRegisterDTO;
import com.lyy.lottery.service.enums.UserIdentityEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
public class UserController {
    private static final Logger logger=LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;
    @Autowired
    private VerificationCodeService verificationCodeService;

    //register.html-注册用户（管理员/普通用户）
    @RequestMapping("/register")
    public CommonResult<UserRegisterResult> userRegister(@Validated @RequestBody UserRegisterParam param){
        //日志打印
        logger.info("userRegister UserRegisterParam:{}",param);
        //调用service层服务进行访问
        UserRegisterDTO userRegisterDTO=userService.register(param);
        return CommonResult.sucess(convertToUserRegisterResult(userRegisterDTO));
    }

    //发送验证码服务
    @RequestMapping("/verification-code/send")
    public CommonResult<Boolean> sendVerification(String phoneNumber){
        logger.info("sendVerification phoneNumber:{}",phoneNumber);
        verificationCodeService.sendVerificationCode(phoneNumber);
        return CommonResult.sucess(Boolean.TRUE);
    }

    //密码登录
    @RequestMapping("/password/login")
    public CommonResult<UserLoginResult> userPasswordLogin(@Validated @RequestBody UserPasswordLoginParam param){
        logger.info("userPasswordLogin UserPasswordLoginParam:{}", JacksonUtil.writeValueAsString(param));
        UserLoginDTO userLoginDTO=userService.login(param);
        return CommonResult.sucess(convertToUserLoginResult(userLoginDTO));
    }

    //短信验证码登录
    @RequestMapping("/message/login")
    public CommonResult<UserLoginResult> shortMessageLogin(@Validated @RequestBody ShortMessageLoginParam param){
        logger.info("shortMessageLogin ShortMessageLoginParam:{}",JacksonUtil.writeValueAsString(param));
        UserLoginDTO userLoginDTO=userService.login(param);
        return CommonResult.sucess(convertToUserLoginResult(userLoginDTO));
    }

    //user-list.html-查询用户列表（identity=null）
    @RequestMapping("/base-user/find-list")
    public CommonResult<List<BaseUserInfoResult>> findBaseUserInfo(String identity){
        logger.info("findBaseUserInfo identity:{}",identity);
        List<UserDTO> userDTOList =userService.findUserInfo(
                UserIdentityEnum.forName(identity)
        );
        return CommonResult.sucess(convertToList(userDTOList));
    }

    private UserRegisterResult convertToUserRegisterResult(UserRegisterDTO userRegisterDTO) {
        UserRegisterResult result=new UserRegisterResult();
        if (null==userRegisterDTO){
            throw new ControllerException(ControllerErrorCodeConstants.REGISTER_ERROR);
        }
        result.setUserId(userRegisterDTO.getUserId());
        return result;
    }

    private UserLoginResult convertToUserLoginResult(UserLoginDTO userLoginDTO) {
        if (null==userLoginDTO){
            throw new ServiceException(ControllerErrorCodeConstants.LOGIN_ERROR);
        }
        UserLoginResult userLoginResult=new UserLoginResult();
        userLoginResult.setToken(userLoginDTO.getToken());
        userLoginResult.setIdentity(userLoginDTO.getIdentity().name());
        return userLoginResult;
    }

    private List<BaseUserInfoResult> convertToList(List<UserDTO> userDTOList) {
        if (CollectionUtils.isEmpty(userDTOList))
            return Arrays.asList();

        return userDTOList.stream().map(
                userDTO -> {
                    BaseUserInfoResult result=new BaseUserInfoResult();
                    result.setUserId(userDTO.getUserId());
                    result.setUserName(userDTO.getUserName());
                    result.setIdentity(userDTO.getIdentity().name());
                    return result;
                }
        ).collect(Collectors.toList());
    }
}





















